#include <ximera/threading/messagequeue.hpp>

namespace ximera { namespace threading 
{
    MessageQueue::MessageQueue(): _deleting(false)
    {
    }

    MessageQueue::~MessageQueue()
    {
        boost::mutex::scoped_lock lock(_mutex);

        _deleting = true;

        while (!_messages.empty())
        {
            IMessage* msg = _messages.front();
            _messages.pop();

            try
            {
                delete msg;
            }
            catch (...) { }
        }
    }

    void MessageQueue::addMessage(IMessage *message)
    {
        boost::mutex::scoped_lock lock(_mutex);

        if (!_deleting)
            _messages.push(message);
    }

    void MessageQueue::processMessages()
    {
        boost::mutex::scoped_lock lock(_mutex);

        if (_deleting) 
            return;

        while (!_messages.empty())
        {
            IMessage* msg = _messages.front();
            _messages.pop();

            try
            {
                msg->process();                
            }
            catch (...) { }

            delete msg;
        }
    }
}}
